import { Http } from '@capacitor-community/http'
import { Capacitor } from '@capacitor/core'
import envConfig from '../config/env'

class ApiService {
  constructor() {
    this.config = envConfig
    this.isNative = Capacitor.isNativePlatform()
    this.isProduction = import.meta.env.PROD
    
    // 缓存管理
    this.cache = new Map()
    this.cacheTimeout = 5 * 60 * 1000 // 5分钟缓存
    
    console.log('API Service initialized:', {
      environment: import.meta.env.VITE_APP_ENV,
      isNative: this.isNative,
      baseURL: this.config.baseURL,
      useProxy: this.config.useProxy
    })
  }

  /**
   * 智能 URL 构建
   */
  buildUrl(url) {
    if (url.startsWith('http')) {
      return url
    }
    
    if (this.config.useProxy && !this.isNative) {
      return `/query${url}`
    }
    
    return `${this.config.baseURL}${url}`
  }

  /**
   * 生成缓存键
   */
  generateCacheKey(method, url, data) {
    const keyData = {
      method,
      url,
      data: this.cleanParams(data || {})
    }
    return JSON.stringify(keyData)
  }

  /**
   * 获取缓存数据
   */
  getFromCache(cacheKey) {
    const cached = this.cache.get(cacheKey)
    if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
      console.log('[Cache] Hit:', cacheKey)
      return cached.data
    }
    
    if (cached) {
      console.log('[Cache] Expired:', cacheKey)
      this.cache.delete(cacheKey)
    }
    
    return null
  }

  /**
   * 设置缓存数据
   */
  setCache(cacheKey, data) {
    this.cache.set(cacheKey, {
      data,
      timestamp: Date.now()
    })
    console.log('[Cache] Set:', cacheKey)
  }

  /**
   * 清除缓存
   */
  clearCache() {
    this.cache.clear()
    console.log('[Cache] Cleared all cache')
  }

  /**
   * 清除特定 URL 的缓存
   */
  clearUrlCache(urlPattern) {
    for (const [key] of this.cache) {
      const cacheData = JSON.parse(key)
      if (cacheData.url.includes(urlPattern)) {
        this.cache.delete(key)
        console.log('[Cache] Cleared:', cacheData.url)
      }
    }
  }

  /**
   * 智能请求方法
   */
  async request(method, url, data = null, options = {}) {
    const fullUrl = this.buildUrl(url)
    const cacheKey = this.generateCacheKey(method, fullUrl, data)
    
    // 检查是否禁用缓存
    const disableCache = options.disableCache || false
    
    // 如果是 GET 请求且启用缓存，先检查缓存
    if (method.toUpperCase() === 'GET' && !disableCache) {
      const cachedData = this.getFromCache(cacheKey)
      if (cachedData) {
        return cachedData
      }
    }

    console.log(`[API] ${method} ${fullUrl}`, {
      data,
      environment: import.meta.env.VITE_APP_ENV,
      isNative: this.isNative,
      useProxy: this.config.useProxy,
      disableCache
    })

    try {
      let response
      
      // 在开发环境浏览器中，使用 fetch 作为备选
      if (!this.isNative && this.config.useProxy) {
        response = await this.browserRequest(method, fullUrl, data, options)
      } else {
        // 原生应用或生产环境使用 Capacitor HTTP
        response = await this.nativeRequest(method, fullUrl, data, options)
      }

      // 处理 304 状态码
      if (response.status === 304) {
        console.log(`[API] 304 Not Modified: ${fullUrl}`)
        
        // 从缓存中获取数据
        const cachedData = this.getFromCache(cacheKey)
        if (cachedData) {
          return cachedData
        } else {
          // 如果没有缓存，重新请求并禁用缓存
          console.log(`[API] No cache found for 304, retrying without cache`)
          return this.request(method, url, data, { ...options, disableCache: true })
        }
      }

      // 缓存成功的 GET 请求
      if (method.toUpperCase() === 'GET' && !disableCache && response.status === 200) {
        this.setCache(cacheKey, response)
      }

      return response
      
    } catch (error) {
      return this.handleError(error, method, url)
    }
  }

  /**
   * 原生请求（Capacitor HTTP）
   */
  async nativeRequest(method, url, data = null, options = {}) {
    const requestOptions = {
      method: method.toUpperCase(),
      url: url,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': options.disableCache ? 'no-cache' : 'max-age=300',
        ...this.getAuthHeaders(),
        ...options.headers
      },
      connectTimeout: this.config.timeout,
      readTimeout: this.config.timeout
    }

    // 处理 GET 和其他方法的参数
    if (method.toUpperCase() === 'GET') {
      requestOptions.params = this.cleanParams(data || options.params || {})
    } else {
      requestOptions.data = data
      requestOptions.params = options.params || {}
    }

    const response = await Http.request(requestOptions)
    return this.handleResponse(response)
  }

  /**
   * 浏览器请求（开发环境）
   */
  async browserRequest(method, url, data = null, options = {}) {
    const config = {
      method: method.toUpperCase(),
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': options.disableCache ? 'no-cache' : 'max-age=300',
        ...this.getAuthHeaders(),
        ...options.headers
      },
      credentials: 'omit'
    }

    // 处理 GET 请求参数
    let requestUrl = url
    if (method.toUpperCase() === 'GET' && data) {
      const params = new URLSearchParams()
      Object.keys(this.cleanParams(data)).forEach(key => {
        params.append(key, data[key])
      })
      requestUrl += '?' + params.toString()
    } else if (data) {
      config.body = JSON.stringify(data)
    }

    console.log(`[Browser API] ${method} ${requestUrl}`, config)

    const response = await fetch(requestUrl, config)
    
    // 处理 304 状态码
    if (response.status === 304) {
      return {
        status: 304,
        data: null,
        message: 'Not Modified'
      }
    }
    
    if (!response.ok) {
      throw new Error(`HTTP Error: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    return {
      status: response.status,
      data: result
    }
  }

  /**
   * 清理参数（移除空值）
   */
  cleanParams(params) {
    const cleaned = {}
    Object.keys(params).forEach(key => {
      if (params[key] !== null && params[key] !== undefined && params[key] !== '') {
        cleaned[key] = params[key]
      }
    })
    return cleaned
  }

  /**
   * GET 请求 - 增强版本
   */
  async get(url, params = {}, options = {}) {
    return this.request('GET', url, params, options)
  }

  /**
   * GET 请求 - 强制刷新（忽略缓存）
   */
  async getFresh(url, params = {}, options = {}) {
    return this.request('GET', url, params, { ...options, disableCache: true })
  }

  /**
   * POST 请求
   */
  async post(url, data = {}, options = {}) {
    // 清除可能受影响的缓存
    this.clearUrlCache(url)

    // POST 请求成功后，清除相关 GET 请求的缓存
    const response = await this.request('POST', url, data, options)

    return response
  }

  /**
   * PUT 请求
   */
  async put(url, data = {}, options = {}) {
    const response = await this.request('PUT', url, data, options)
    
    // 清除可能受影响的缓存
    this.clearUrlCache(url)
    
    return response
  }

  /**
   * DELETE 请求
   */
  async delete(url, data = {}, options = {}) {
    const response = await this.request('DELETE', url, data, options)
    
    // 清除可能受影响的缓存
    this.clearUrlCache(url)
    
    return response
  }

  /**
   * 专用查询方法 - 播放列表
   */
  async queryPlayList(params = {}, options = {}) {
    return this.get('/query/QueryPlayList', params, options)
  }

  /**
   * 强制刷新播放列表（忽略缓存）
   */
  async queryPlayListFresh(params = {}, options = {}) {
    return this.getFresh('/query/QueryPlayList', params, options)
  }

  /**
   * 健康检查
   */
  async healthCheck() {
    try {
      const result = await this.get('/health', {}, { disableCache: true, timeout: 5000 })
      return { success: true, data: result }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  /**
   * 获取认证头信息
   */
  getAuthHeaders() {
    const token = localStorage.getItem('authToken')
    const headers = {}

    if (token) {
      headers['Authorization'] = `Bearer ${token}`
    }

    return headers
  }

  /**
   * 处理响应
   */
  handleResponse(response) {
    // 304 状态码已经在 request 方法中处理
    if (response.status === 304) {
      return response
    }
    
    if (response.status >= 200 && response.status < 300) {
      return response.data
    } else {
      throw new Error(`HTTP Error: ${response.status}`)
    }
  }

  /**
   * 错误处理
   */
  handleError(error, method, url) {
    console.error(`[API Error] ${method} ${url}:`, error)

    let errorMessage = '请求失败，请重试'
    let errorType = 'UNKNOWN_ERROR'
    
    if (error.message && error.message.includes('CORS')) {
      errorMessage = '跨域请求被阻止，请检查网络连接'
      errorType = 'CORS_ERROR'
    } else if (error.message && error.message.includes('NETWORK')) {
      errorMessage = '网络连接失败，请检查网络设置'
      errorType = 'NETWORK_ERROR'
    } else if (error.message && error.message.includes('TIMEOUT')) {
      errorMessage = '请求超时，请检查网络连接'
      errorType = 'TIMEOUT_ERROR'
    } else if (error.message && error.message.includes('certificate')) {
      errorMessage = 'SSL证书验证失败'
      errorType = 'SSL_ERROR'
    } else if (error.message && error.message.includes('404')) {
      errorMessage = '请求的资源不存在'
      errorType = 'NOT_FOUND'
    } else if (error.message && error.message.includes('500')) {
      errorMessage = '服务器内部错误，请稍后重试'
      errorType = 'SERVER_ERROR'
    } else if (error.message && error.message.includes('304')) {
      errorMessage = '数据未修改，使用缓存数据'
      errorType = 'NOT_MODIFIED'
      // 304 不是错误，返回特殊标识
      return { __notModified: true, message: '数据未修改' }
    }

    this.showError(errorMessage)
    
    const enhancedError = new Error(errorMessage)
    enhancedError.type = errorType
    enhancedError.originalError = error
    
    throw enhancedError
  }

  /**
   * 显示错误信息
   */
  showError(message) {
    if (typeof window !== 'undefined' && window.alert) {
      window.alert(message)
    }
    console.error('API Error:', message)
  }
}

// 创建单例实例
export const apiService = new ApiService()
